package com.sendpo.zjx.sendpo.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.BuildConfig;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.UserDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import me.shaohui.bottomdialog.BottomDialog;

/**
 * Created by zjx on 2018
 */

public class UserProfileActivity extends AppCompatActivity {
    public final int REQUEST_CAMERA = 104;
    public final int REQUEST_CROP = 105;
    public final int REQUEST_IMAGECOUNT = 1031;
    public final int MODIFY_NICHENG = 101;
    public final int MODIFY_SIGNTEXT = 100;
    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.shiping_level)
    TextView shipingLevel;
    @BindView(R.id.cir_iv)
    ImageView cirIv;
    @BindView(R.id.cir_icon)
    CircleImageView cirIcon;
    @BindView(R.id.shiming_bt)
    RelativeLayout shimingBt;
    @BindView(R.id.acnumber_tv)
    TextView acnumberTv;
    @BindView(R.id.unamecir_iv)
    ImageView unamecirIv;
    @BindView(R.id.uname)
    TextView uname;
    @BindView(R.id.acnumber_bt)
    RelativeLayout acnumberBt;
    @BindView(R.id.sign_tv)
    TextView signTv;
    @BindView(R.id.sign_iv)
    ImageView signIv;
    @BindView(R.id.sign)
    TextView sign;
    @BindView(R.id.sign_bt)
    RelativeLayout signBt;
    @BindView(R.id.sex_tv)
    TextView sexTv;
    @BindView(R.id.sex_iv)
    ImageView sexIv;
    @BindView(R.id.sex)
    TextView sex;
    @BindView(R.id.sex_bt)
    RelativeLayout sexBt;
    @BindView(R.id.age_tv)
    TextView ageTv;
    @BindView(R.id.age_iv)
    ImageView ageIv;
    @BindView(R.id.age)
    TextView age;
    @BindView(R.id.age_bt)
    RelativeLayout ageBt;
    private Dialog age_dialog;
    private BottomDialog bottomDialog;
    public Dialog loadingdialog = null;
    private BottomDialog sex_dialog;
    File temp_cmera = null;
    private EditText edit_age;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Tools.initStatus(this, R.color.black);
        setContentView(R.layout.activity_personfile);
        ButterKnife.bind(this);
        initComponent();
    }

    private void initComponent() {
        this.loadingdialog = new Dialog(this);
        this.loadingdialog.setContentView(R.layout.dialog_loading);
        this.loadingdialog.setCanceledOnTouchOutside(false);
        this.loadingdialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        showOpenDialog();
        this.age_dialog = new Dialog(this);
        this.age_dialog.setContentView(R.layout.dialog_age);
        this.age_dialog.setCanceledOnTouchOutside(false);
        this.age_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        this.edit_age = ((EditText)this.age_dialog.findViewById(R.id.edit_tv));
        View localView = this.age_dialog.findViewById(R.id.readby);
        this.age_dialog.findViewById(R.id.exitbt).setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View paramAnonymousView)
            {
                UserProfileActivity.this.age_dialog.dismiss();
            }
        });
        localView.setOnClickListener(new View.OnClickListener() {
            public void onClick(View paramAnonymousView) {
                if (TextUtils.isEmpty(UserProfileActivity.this.edit_age.getText().toString().trim()))
                {
                    Toast.makeText(UserProfileActivity.this.getApplicationContext(), "年龄不能都是空的", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!Tools.isInteger(UserProfileActivity.this.edit_age.getText().toString().trim()))
                {
                    Toast.makeText(UserProfileActivity.this.getApplicationContext(), "不是一个数字", Toast.LENGTH_SHORT).show();
                    return;
                }
                modfiyAge(UserProfileActivity.this.edit_age.getText().toString().trim());
                age.setText(UserProfileActivity.this.edit_age.getText().toString().trim());
                age_dialog.dismiss();
            }
        });
    }

    @OnClick(value = {R.id.backbt,R.id.sex_bt,R.id.age_bt,R.id.shiming_bt,R.id.acnumber_bt,R.id.sign_bt})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                   finish();
                break;
            case R.id.sex_bt:
                sex_dialog.show();
                break;
            case R.id.age_bt:
                age_dialog.show();
                break;
            case R.id.shiming_bt:;
               bottomDialog.show();
            break;
            case R.id.acnumber_bt:
                startActivityForResult(new Intent(this, UserModifyNichengActivity.class), MODIFY_NICHENG);
                break;
            case R.id.sign_bt:
                startActivityForResult(new Intent(this, UserModifySigntextActivity.class), MODIFY_SIGNTEXT);

                break;


        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        locationUserServer();
        webUserSserver();
    }

    public void webUserSserver() {
        final List localList = Xutils.queryAll(getApplication(), User.class);
        if ((localList == null) || (localList.size() == 0)) {
            return;
        }
        final User localUser = (User) localList.get(0);
        Map<String, String> map = new HashMap<>();
        map.put("userId", localUser.getUserId() + "");
        Xutils.POST(HttpUrl.queryuserbyid, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                Gson gson = new Gson();
                UserDomain domain = gson.fromJson(result, UserDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        User data = domain.getData();
                        data.setId(localUser.getId());
                        Xutils.update(getApplication(), data);
                        locationUserServer();

                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void locationUserServer() {
        List<User> userList = Xutils.queryAll(getApplication(), User.class);
        if (userList == null || userList.size() == 0) {
            return;
        }
        User user = userList.get(0);
        if (!TextUtils.isEmpty(user.getUserAvatarpath())) {
            Glide.with(this).load(user.getUserAvatarpath()).asBitmap().animate(R.anim.fade_in).centerCrop().error(R.drawable.nim_avatar_default)
                    .override(300, 300)
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            cirIcon.setImageBitmap(resource);
                        }

                    });
        } else {
            cirIcon.setImageResource(R.drawable.nim_avatar_default);
        }
        uname.setText(user.getUserName());
        age.setText(user.getUserAge() + "");
         if(user.getUserSex()==0){
             this.sex.setText("男");
         }else{
             this.sex.setText("女");
         }
         if(TextUtils.isEmpty(user.getUserSigntext())){
             this.sign.setText("这个人很懒并没有留下什么。。。。");
         }else{
             this.sign.setText("" +user.getUserSigntext());
         }

    }


    public void showOpenDialog() {

        bottomDialog = BottomDialog.create(getSupportFragmentManager());
        bottomDialog.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomDialog.dismiss();
                    }
                });
                View camera = v.findViewById(R.id.camera);
                camera.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        temp_cmera = new File(getExternalCacheDir().getAbsolutePath()+"/" + UUID.randomUUID().toString().substring(0, 10) + ".jpg");
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent.putExtra("return-data", true);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            Uri contentUri = FileProvider.getUriForFile(UserProfileActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider",temp_cmera);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
                        } else {
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(temp_cmera));
                        }
                        startActivityForResult(intent, REQUEST_CAMERA);
                        bottomDialog.dismiss();
                    }
                });
                View exit = v.findViewById(R.id.exit);
                exit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomDialog.dismiss();
                    }
                });
                View imgcontent = v.findViewById(R.id.imgcontent);
                imgcontent.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
                        intent.setType("image/*");
                        intent.putExtra("return-data", true);
                        startActivityForResult(intent, REQUEST_IMAGECOUNT);
                        bottomDialog.dismiss();
                    }
                });
            }
        });
        bottomDialog.setLayoutRes(R.layout.dialog_uploadimg);
        bottomDialog.setDimAmount(0.5f);
        bottomDialog.setCancelOutside(true);
        bottomDialog.setTag("BottomDialog");



        this.sex_dialog = BottomDialog.create(getSupportFragmentManager());
        this.sex_dialog.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                v.setOnClickListener(new View.OnClickListener()
                {
                    public void onClick(View paramAnonymous2View)
                    {
                        sex_dialog.dismiss();
                    }
                });
                v.findViewById(R.id.male).setOnClickListener(new View.OnClickListener()
                {
                    public void onClick(View paramAnonymous2View)
                    {
                        UserProfileActivity.this.sex.setText("男");
                        modfiySex("0");
                        UserProfileActivity.this.sex_dialog.dismiss();
                    }
                });
                v.findViewById(R.id.female).setOnClickListener(new View.OnClickListener()
                {
                    public void onClick(View paramAnonymous2View)
                    {
                        UserProfileActivity.this.sex.setText("女");
                        modfiySex("1");
                        UserProfileActivity.this.sex_dialog.dismiss();
                    }
                });
                v.findViewById(R.id.exit).setOnClickListener(new View.OnClickListener()
                {
                    public void onClick(View paramAnonymous2View)
                    {
                        UserProfileActivity.this.sex_dialog.dismiss();
                    }
                });
            }
        });

        this.sex_dialog.setLayoutRes(R.layout.dialog_sex);
        this.sex_dialog.setDimAmount(0.5F);
        this.sex_dialog.setCancelOutside(true);
        this.sex_dialog.setTag("BottomDialossssg");

    }
    public void modfiySex(String userSex) {
        List<User> userList = Xutils.queryAll(getApplication(), User.class);
        if (userList == null || userList.size() == 0) {
            return;
        }
        User user = userList.get(0);
        Map<String,String> map = new HashMap();
        map.put("userId", user.getUserId() + "");
        map.put("userSex", userSex);
        Xutils.POST(HttpUrl.usermodifysex, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject=new JSONObject(result);
                switch (jsonObject.getInt("state")){
                    case HttpCode.SUCCESS:
                     webUserSserver();
                        break;
                }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(UserProfileActivity.this.getApplicationContext(), "请稍后再试", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }


    public void modfiyAge(String userAge) {
        List<User> userList = Xutils.queryAll(getApplication(), User.class);
        if (userList == null || userList.size() == 0) {
            return;
        }
        User user = userList.get(0);
        Map<String,String> map=new HashMap<>();
        map.put("userId", user.getUserId() + "");
        map.put("userAge", userAge);
        Xutils.POST(HttpUrl.usermodifyage, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject=new JSONObject(result);
                 switch (jsonObject.getInt("state")){
                     case HttpCode.SUCCESS:
                        webUserSserver();
                         break;
                 }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(UserProfileActivity.this.getApplicationContext(), R.string.please_wait, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
               if(resultCode!=RESULT_OK){
                   return;
               }
               final List<User> userList=Xutils.queryAll(getApplication(),User.class);
               if(userList==null||userList.size()==0){
                   return;
               }
        switch (requestCode) {
            case REQUEST_IMAGECOUNT:
                Uri datauri = data.getData();
                final File finalFile1 = new File(getExternalCacheDir().getAbsolutePath() + "/" + UUID.randomUUID().toString().substring(0,10)+".png");;
                Glide.with(this)
                        .load(datauri)
                        .asBitmap()
                        .override(500, 500)
                        .placeholder(getResources().getColor(R.color.default_lightgray))
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                try {
                                    Bitmap bitmap=null;
                                    if(resource.getHeight()<500){
                                        bitmap= Tools.zoomBitmap(resource,resource.getWidth()/1,resource.getHeight()/1);
                                    }else if(resource.getHeight()<1000){
                                        bitmap= Tools.zoomBitmap(resource,resource.getWidth()/2,resource.getHeight()/2);
                                    }else {
                                        bitmap= Tools.zoomBitmap(resource,resource.getWidth()/3,resource.getHeight()/3);
                                    }
                                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(finalFile1));
                                    uploadIcon(userList.get(0).getUserId() + "",finalFile1);
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                break;

            case REQUEST_CAMERA:
                Intent bgcamera = new Intent("com.android.camera.action.CROP");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    bgcamera.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(UserProfileActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider",temp_cmera);
                    bgcamera.setDataAndType(contentUri, "image/*");
                } else {
                    bgcamera.setDataAndType(Uri.fromFile(temp_cmera), "image/*");
                }
                bgcamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(temp_cmera));
                bgcamera.putExtra("return-data", false);
                bgcamera.putExtra("scale", true);
                bgcamera.putExtra("outputFormat", Bitmap.CompressFormat.PNG);
                bgcamera.putExtra("noFaceDetection", true);
               bgcamera.putExtra("aspectX",1);
                 bgcamera.putExtra("aspectY",1);
                bgcamera.putExtra("outputX", 500);
                bgcamera.putExtra("outputY", 500);
                startActivityForResult(bgcamera, REQUEST_CROP);
                break;

            case REQUEST_CROP:
                Glide.with(this)
                        .load(temp_cmera.getPath())
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                Bitmap bitmap=null;
                                if(resource.getHeight()<500){
                                    bitmap= Tools.zoomBitmap(resource,resource.getWidth()/1,resource.getHeight()/1);
                                }else if(resource.getHeight()<1000){
                                    bitmap= Tools.zoomBitmap(resource,resource.getWidth()/2,resource.getHeight()/2);
                                }else {
                                    bitmap= Tools.zoomBitmap(resource,resource.getWidth()/3,resource.getHeight()/3);
                                }
                                try {
                                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(temp_cmera));
                                  uploadIcon(userList.get(0).getUserId()+"",temp_cmera);
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                break;
            case MODIFY_NICHENG:
                if (data != null) {
                    String  nic=data.getStringExtra("data");
                    this.uname.setText(nic);
                    webUserSserver();
                }

                break;
            case MODIFY_SIGNTEXT:
                if (data != null) {
                    String  sign=data.getStringExtra("data");
                    this.sign.setText(sign);
                    webUserSserver();
                }

                break;


        }


    }

    public void uploadIcon(String userId,File file) {
        this.loadingdialog.show();
        HashMap map = new HashMap();
        map.put("userId", userId);
        map.put("files", file);
        Xutils.UpLoadFile(HttpUrl.uploaduseravatarpathbyid, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                UserProfileActivity.this.loadingdialog.dismiss();
                try {
                    JSONObject jsonObject=new JSONObject(result);
                switch (jsonObject.getInt("state")){
                    case HttpCode.SUCCESS:
                        webUserSserver();
                        break;
                }
                    Toast.makeText(UserProfileActivity.this.getApplicationContext(),jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                UserProfileActivity.this.loadingdialog.dismiss();
                Toast.makeText(UserProfileActivity.this.getApplicationContext(), getResources().getString(R.string.please_wait), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

}
